import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { Button, Table, message } from 'antd';

export default function Audit() {
  const [dataSource, setdataSource] = useState([])
  const { roleId, region, username } = JSON.parse(localStorage.getItem('token'))
  // 获得自己且职位比自己低的新闻数据
  useEffect(() => {
    axios.get(`/news?auditState=1&_expand=category`).then(res => {
      console.log(res.data)
      const list = res.data
      setdataSource(roleId === 1 ? list : [
        ...list.filter(item => item.author === username),
        ...list.filter(item => item.region === region && item.roleId === 3)
      ])
    })
  }, [roleId, region, username])

  // 表格数据
  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      key: 'title',
      render: (title, item) => <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (item) => item.title
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Button type='primary' onClick={() => handleNew(item, 2, 1)}>通过</Button>
          <Button type='primary' danger onClick={() => handleNew(item, 3, 0)}>拒绝</Button>
        </div>
      }
    },
  ];

  // 拒绝和通过
  const handleNew = (item, auditState, publishState) => {
    // console.log(item)
    setdataSource(dataSource.filter(i => i.id !== item.id))
    axios.patch(`/news/${item.id}`, {
      auditState,
      publishState
    }).then(res => {
      message.info('去审核列表查看')
    })
  }
  return (
    <div>
      <Table dataSource={dataSource} columns={columns} rowKey={item => item.id} pagination={{ pageSize: 5 }} />;
    </div>
  )
}
